<!DOCTYPE html>

<html class="theme-next mist use-motion" lang="zh-Hans">

<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
                                                                                  content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="theme-color" content="#222">

  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">

  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet"
                                                                                  type="text/css">

  <link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet"
                                                                                  type="text/css">

  <link href="/css/main.css?v=6.0.1" rel="stylesheet" type="text/css">

  <link rel="icon" type="image/png" sizes="16x16"
                                                                                  href="/images/favicon.ico?v=6.0.1">

  <script type="text/javascript" id="hexo.configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      root: '/',
      scheme: 'Mist',
      version: '6.0.1',
      sidebar: {
        "position": "left",
        "display": "post",
        "offset": 12,
        "b2t": true,
        "scrollpercent": true,
        "onmobile": true
      },
      fancybox: true,
      fastclick: false,
      lazyload: true,
      tabs: true,
      motion: {
        "enable": true,
        "async": false,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "slideDownIn",
          "post_body": "slideDownIn",
          "coll_header": "slideLeftIn",
          "sidebar": "slideUpIn"
        }
      },
      algolia: {
        applicationID: '',
        apiKey: '',
        indexName: '',
        hits: {
          "per_page": 10
        },
        labels: {
          "input_placeholder": "Search for Posts",
          "hits_empty": "We didn't find any results for the search: ${query}",
          "hits_stats": "${hits} results found in ${time} ms"
        }
      }
    };

  </script>

  <link rel="stylesheet" href="mermaid.min.css">
  <script src="https://unpkg.com/mermaid@7.1.0/dist/mermaid.min.js"></script>

  <meta name="keywords" content="python,python-eve,web,">

  <meta name="description" content="实在找不到图了……">
  <meta name="keywords" content="python,python-eve,web">
  <meta property="og:type" content="article">
  <meta property="og:title" content="python-eve 最佳实践">
  <meta property="og:url"
                                                                                  content="https://tankeryang.github.io/posts/python-eve-最佳实践/index.html">
  <meta property="og:site_name" content="淦">
  <meta property="og:description" content="实在找不到图了……">
  <meta property="og:locale" content="zh-Hans">
  <meta property="og:image"
                                                                                  content="https://tankeryang.github.io/posts/python-eve-最佳实践/pic0.png">
  <meta property="og:image"
                                                                                  content="https://tankeryang.github.io/posts/python-eve-最佳实践/pic1.png">
  <meta property="og:updated_time" content="2019-10-09T17:06:09.611Z">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="python-eve 最佳实践">
  <meta name="twitter:description" content="实在找不到图了……">
  <meta name="twitter:image"
                                                                                  content="https://tankeryang.github.io/posts/python-eve-最佳实践/pic0.png">

  <title>python-eve 最佳实践 | 淦</title>

  <noscript>
    <style type="text/css">
      .use-motion .motion-element,
      .use-motion .brand,
      .use-motion .menu-item,
      .sidebar-inner,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-title {
        opacity: initial;
      }

      .use-motion .logo,
      .use-motion .site-title,
      .use-motion .site-subtitle {
        opacity: initial;
        top: initial;
      }

      .use-motion {
        .logo-line-before i {
          left: initial;
        }

        .logo-line-after i {
          right: initial;
        }
      }

    </style>
  </noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope
                                                                                    itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-wrapper">
          <div class="site-meta ">

            <div class="custom-logo-site-title">
              <a href="/" class="brand" rel="start">
                <span class="logo-line-before"><i></i></span>
                <span class="site-title">淦</span>
                <span class="logo-line-after"><i></i></span>
              </a>
            </div>

            <p class="site-subtitle">n*m*lg(b)</p>

          </div>

          <div class="site-nav-toggle">
            <button>
              <span class="btn-bar"></span>
              <span class="btn-bar"></span>
              <span class="btn-bar"></span>
            </button>
          </div>
        </div>

        <nav class="site-nav">

          <ul id="menu" class="menu">

            <li class="menu-item menu-item-home">
              <a href="/" rel="section">
                <i class="menu-item-icon fa fa-fw fa-home"></i> <br>home</a>
            </li>

            <li class="menu-item menu-item-archives">
              <a href="/archives/" rel="section">
                <i class="menu-item-icon fa fa-fw fa-archive"></i>
                <br>archives<span class="badge">16</span>
              </a>
            </li>

            <li class="menu-item menu-item-ml-note">
              <a href="/MachineLearningNote" rel="section">
                <i class="menu-item-icon fa fa-fw fa-book"></i> <br>ML Note</a>
            </li>

            <li class="menu-item menu-item-about">
              <a href="/about/" rel="section">
                <i class="menu-item-icon fa fa-fw fa-user"></i> <br>about</a>
            </li>

            <li class="menu-item menu-item-search">

              <a href="javascript:;" class="popup-trigger">

                <i class="menu-item-icon fa fa-search fa-fw"></i> <br>search</a>
            </li>

          </ul>

          <div class="site-search">

            <div class="popup search-popup local-search-popup">
              <div class="local-search-header clearfix">
                <span class="search-icon">
                  <i class="fa fa-search"></i>
                </span>
                <span class="popup-btn-close">
                  <i class="fa fa-times-circle"></i>
                </span>
                <div class="local-search-input-wrapper">
                  <input autocomplete="off" placeholder="searching..." spellcheck="false" type="text"
                                                                                                  id="local-search-input">
                </div>
              </div>
              <div id="local-search-result"></div>
            </div>

          </div>

        </nav>
      </div>
    </header>

    <a href="https://github.com/tankeryang" class="github-corner" target="_blank" title="Follow me on GitHub"
                                                                                    aria-label="Follow me on GitHub"><svg
                                                                                      width="80"
                                                                                      height="80"
                                                                                      viewbox="0 0 250 250"
                                                                                      style="fill:#222; color:#fff; position: absolute; top: 0; border: 0; right: 0;"
                                                                                      aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z" />
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
                                                                                        fill="currentColor"
                                                                                        style="transform-origin: 130px 106px;"
                                                                                        class="octo-arm" />
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
                                                                                        fill="currentColor"
                                                                                        class="octo-body" />
        </svg></a>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">

            <div id="posts" class="posts-expand">

              <div class="reading-progress-bar"></div>

              <article class="post post-type-normal" itemscope
                                                                                              itemtype="http://schema.org/Article">

                <div class="post-block">
                  <link itemprop="mainEntityOfPage"
                                                                                                  href="https://tankeryang.github.io/posts/python-eve-最佳实践/">

                  <span hidden itemprop="author" itemscope
                                                                                                  itemtype="http://schema.org/Person">
                    <meta itemprop="name" content="tankeryang">
                    <meta itemprop="description" content>
                    <meta itemprop="image" content="/uploads/girl.jpeg">
                  </span>

                  <span hidden itemprop="publisher" itemscope
                                                                                                  itemtype="http://schema.org/Organization">
                    <meta itemprop="name" content="淦">
                  </span>

                  <header class="post-header">

                    <h1 class="post-title" itemprop="name headline">python-eve
                      最佳实践</h1>

                    <div class="post-meta">
                      <span class="post-time">

                        <span class="post-meta-item-icon">
                          <i class="fa fa-calendar-o"></i>
                        </span>

                        <span class="post-meta-item-text">posted on</span>

                        <time title="创建于" itemprop="dateCreated datePublished"
                                                                                                        datetime="2019-08-22T23:06:57+00:00">2019-08-22</time>

                      </span>

                      <span class="post-comments-count">
                        <span class="post-meta-divider">|</span>
                        <span class="post-meta-item-icon">
                          <i class="fa fa-comment-o"></i>
                        </span>
                        <a href="/posts/python-eve-最佳实践/#comments"
                                                                                                        itemprop="discussionUrl">
                          <span class="post-comments-count valine-comment-count" data-xid="/posts/python-eve-最佳实践/"
                                                                                                          itemprop="commentCount"></span>
                        </a>
                      </span>

                      <span id="/posts/python-eve-最佳实践/" class="leancloud_visitors"
                                                                                                      data-flag-title="python-eve 最佳实践">
                        <span class="post-meta-divider">|</span>
                        <span class="post-meta-item-icon">
                          <i class="fa fa-eye"></i>
                        </span>

                        <span class="post-meta-item-text">read times&#58;</span>

                        <span class="leancloud-visitors-count"></span>
                      </span>

                      <div class="post-wordcount">

                        <span class="post-meta-item-icon">
                          <i class="fa fa-file-word-o"></i>
                        </span>

                        <span class="post-meta-item-text">words
                          count&#58;</span>

                        <span title="words count">21k</span>

                        <span class="post-meta-divider">|</span>

                        <span class="post-meta-item-icon">
                          <i class="fa fa-clock-o"></i>
                        </span>

                        <span class="post-meta-item-text">minutes to read
                          &asymp;</span>

                        <span title="minutes to read">0:47</span>

                      </div>

                    </div>
                  </header>

                  <div class="post-body" itemprop="articleBody">

                    <img src="/posts/python-eve-最佳实践/pic0.png">
                    <p>实在找不到图了……</p>
                    <a id="more"></a>
                    <p>最近因为工作的关系，被要求用到 <a href="https://docs.python-eve.org/en/stable/" target="_blank"
                                                                                                      rel="noopener">Eve</a>
                      这个框架，需求简要概括就是对一个 mongo 表的 crud，本来用 flask 直接一把梭完就一个下午的事，但因为
                      “工作” 的关系，不得不盘一下
                      <strong>Eve</strong></p>
                    <h1 id="Eve-简介"><a href="#Eve-简介" class="headerlink"
                                                                                                      title="Eve 简介"></a>Eve
                      简介
                    </h1>
                    <p>详细看了 Eve 的源码，他是一个对 <strong>Flask</strong> 高度定制化的，以
                      <strong>配置</strong> 为驱动的
                      restful 框架，根据配置文件生成 <strong>endpoint url</strong> 和
                      <strong>endpoint
                        method</strong>，以 <strong>http method</strong> 对应
                      <strong>crud</strong>
                      操作。<strong>Eve</strong> 的数据持久化原生支持
                      <strong>mongodb</strong>，配置了
                      <strong>mongo</strong> 相关的参数后，对 <strong>endpoint
                        url</strong> 的请求操作相当于直接对对应的
                      mongo 表进行 crud</p>
                    <p>下面上官方文档的例子进行说明</p>
                    <h2 id="快速开始"><a href="#快速开始" class="headerlink"
                                                                                                      title="快速开始"></a>快速开始
                    </h2>
                    <ul>
                      <li>
                        <p>先启动一个 mongodb，这里用 docker 启一个 mongodb 容器 (这里选 3.4
                          版本的和公司一致，你可以自行选择其他版本)
                        </p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&gt; $ docker run --name mongodb -p 27017:27017 \</span><br><span class="line">    -v /srv/mongodb/etc:/etc/mongo \</span><br><span class="line">    -v /srv/mongo/data/db:/data/db \</span><br><span class="line">    -e MONGO_INITDB_ROOT_USERNAME=admin \</span><br><span class="line">    -e MONGO_INITDB_ROOT_PASSWORD=admin123 \</span><br><span class="line">    -d mongo:3.4-xenial</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                      <li>
                        <p>进入容器，创建 <code>test</code> 数据库，并设置用户
                          <code>test</code>，密码
                          <code>test123</code></p>
                        <ul>
                          <li>
                            <p>进入容器的 mongodb 交互终端</p>
                            <figure class="highlight bash">
                              <table>
                                <tr>
                                  <td class="gutter">
                                    <pre><span class="line">1</span><br></pre>
                                  </td>
                                  <td class="code">
                                    <pre><span class="line">&gt; $ docker <span class="built_in">exec</span> -it mongodb mongo -u admin -p admin123 --authenticationDatabase admin</span><br></pre>
                                  </td>
                                </tr>
                              </table>
                            </figure>
                          </li>
                          <li>
                            <p>创建 <code>test</code> 数据库，并设置用户
                              <code>test</code>，密码
                              <code>test123</code></p>
                            <figure class="highlight bash">
                              <table>
                                <tr>
                                  <td class="gutter">
                                    <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                                  </td>
                                  <td class="code">
                                    <pre><span class="line">&gt; use <span class="built_in">test</span></span><br><span class="line">&gt; db.createUser(&#123;user: <span class="string">'test'</span>, <span class="built_in">pwd</span>: <span class="string">'test123'</span>, roles:[&#123;role: <span class="string">'readWrite'</span>, db: <span class="string">'test'</span>&#125;]&#125;)</span><br></pre>
                                  </td>
                                </tr>
                              </table>
                            </figure>
                          </li>
                        </ul>
                      </li>
                      <li>
                        <p>假设你当前目录为 <code>workspace</code>，在这个目录下新建
                          <code>settings.py</code>
                          文件，顾名思义，这就是 <strong>配置文件</strong></p>
                        <blockquote>
                          <p>文件名可以自定义，在初始化 Eve 对象的时候传进去就好了，默认是
                            <code>settings.py</code></p>
                        </blockquote>
                        <figure class="highlight python">
                          <figcaption><span>settings.py</span></figcaption>
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line"><span class="comment"># 下面为 mongo 相关配置</span></span><br><span class="line">MONGO_HOST = <span class="string">'localhost'</span></span><br><span class="line">MONGO_PORT = <span class="number">27017</span></span><br><span class="line">MONGO_USERNAME = <span class="string">'test'</span></span><br><span class="line">MONGO_PASSWORD = <span class="string">'test123'</span></span><br><span class="line">MONGO_AUTH_SOURCE = <span class="string">'test'</span></span><br><span class="line">MONGO_DBNAME = <span class="string">'test'</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 定义 resource 和 item 能够接受的 http method</span></span><br><span class="line"><span class="comment"># 这里统一规定，resource 相当于 mongo collection，item 相当于 mongo document</span></span><br><span class="line">RESOURCE_METHODS = [<span class="string">'GET'</span>, <span class="string">'POST'</span>, <span class="string">'DELETE'</span>]</span><br><span class="line">ITEM_METHODS = [<span class="string">'GET'</span>, <span class="string">'PATCH'</span>, <span class="string">'PUT'</span>, <span class="string">'DELETE'</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 定义 item schema，schema 相当于 mongo document 的字段定义</span></span><br><span class="line">schema = &#123;</span><br><span class="line">    <span class="string">'firstname'</span>: &#123;</span><br><span class="line">        <span class="string">'type'</span>: <span class="string">'string'</span>,</span><br><span class="line">        <span class="string">'minlength'</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="string">'maxlength'</span>: <span class="number">10</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">'lastname'</span>: &#123;</span><br><span class="line">        <span class="string">'type'</span>: <span class="string">'string'</span>,</span><br><span class="line">        <span class="string">'minlength'</span>: <span class="number">1</span>,</span><br><span class="line">        <span class="string">'maxlength'</span>: <span class="number">15</span>,</span><br><span class="line">        <span class="string">'required'</span>: <span class="literal">True</span>,</span><br><span class="line">        <span class="string">'unique'</span>: <span class="literal">True</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">'role'</span>: &#123;</span><br><span class="line">        <span class="string">'type'</span>: <span class="string">'list'</span>,</span><br><span class="line">        <span class="string">'allowed'</span>: [<span class="string">"author"</span>, <span class="string">"contributor"</span>, <span class="string">"copy"</span>],</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">'location'</span>: &#123;</span><br><span class="line">        <span class="string">'type'</span>: <span class="string">'dict'</span>,</span><br><span class="line">        <span class="string">'schema'</span>: &#123;</span><br><span class="line">            <span class="string">'address'</span>: &#123;<span class="string">'type'</span>: <span class="string">'string'</span>&#125;,</span><br><span class="line">            <span class="string">'city'</span>: &#123;<span class="string">'type'</span>: <span class="string">'string'</span>&#125;</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">'born'</span>: &#123;</span><br><span class="line">        <span class="string">'type'</span>: <span class="string">'datetime'</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 定义 resource，名为 people</span></span><br><span class="line">people = &#123;</span><br><span class="line">    <span class="string">'item_title'</span>: <span class="string">'person'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 默认的请求 item 的 endpoint path 为 '/people/&lt;mongo ObjectId&gt;'，这样不太方便，</span></span><br><span class="line">    <span class="comment"># 我们可以自定义 item 的 endpoint path，这里用 lastname，因为是 unique 字段</span></span><br><span class="line">    <span class="string">'additional_lookup'</span>: &#123;</span><br><span class="line">        <span class="string">'url'</span>: <span class="string">'regex("[\w]+")'</span>,</span><br><span class="line">        <span class="string">'field'</span>: <span class="string">'lastname'</span></span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># cache 相关</span></span><br><span class="line">    <span class="string">'cache_control'</span>: <span class="string">'max-age=10,must-revalidate'</span>,</span><br><span class="line">    <span class="string">'cache_expires'</span>: <span class="number">10</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 这里会覆盖上面定义的全局 RESOURCE_METHOD</span></span><br><span class="line">    <span class="string">'resource_methods'</span>: [<span class="string">'GET'</span>, <span class="string">'POST'</span>],</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 指定 schema</span></span><br><span class="line">    <span class="string">'schema'</span>: schema</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 定义 domain，相当于将 people resource 绑定到 ‘people’ 这个 resource endpoint</span></span><br><span class="line">DOMAIN = &#123;<span class="string">'people'</span>: people&#125;</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                      <li>
                        <p>接着新建 <code>main.py</code> 文件</p>
                        <blockquote>
                          <p>同样文件名可自定义，这个文件主要实例化 Eve 对象，相当于入口文件</p>
                        </blockquote>
                        <figure class="highlight python">
                          <figcaption><span>main.py</span></figcaption>
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line"><span class="keyword">from</span> eve <span class="keyword">import</span> Eve</span><br><span class="line">app = Eve()</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    app.run()</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                      <li>
                        <p>执行 <code>main.py</code> 这个脚本</p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&gt; $ python main.py</span><br><span class="line"></span><br><span class="line">* Serving Flask app <span class="string">"eve"</span> (lazy loading)</span><br><span class="line">* Environment: production</span><br><span class="line">WARNING: This is a development server. Do not use it <span class="keyword">in</span> a production deployment.</span><br><span class="line">Use a production WSGI server instead.</span><br><span class="line">* Debug mode: off</span><br><span class="line">* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                      <li>
                        <p><code>curl</code> 测试一下 api</p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&gt; $ curl -i http://127.0.0.1:5000/</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 如果没有意外的话，你会得到下面的返回</p>
                        <figure class="highlight json">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">HTTP/1.0 200 OK</span><br><span class="line">Content-Type: application/json</span><br><span class="line">Content-Length: 62</span><br><span class="line">Server: Eve/0.9.2 Werkzeug/0.15.4 Python/3.6.8</span><br><span class="line">Date: Fri, 23 Aug 2019 09:32:08 GMT</span><br><span class="line"></span><br><span class="line">&#123;<span class="attr">"_links"</span>: &#123;<span class="attr">"child"</span>: [&#123;<span class="attr">"href"</span>: <span class="string">"people"</span>, <span class="attr">"title"</span>: <span class="string">"people"</span>&#125;]&#125;&#125;</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 请求一下 <code>people</code> 资源</p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&gt; $ curl http://127.0.0.1:5000/people</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 如果没有意外的话，你会得到下面的返回</p>
                        <figure class="highlight json">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">"_items"</span>: [],</span><br><span class="line">    <span class="attr">"_links"</span>: &#123;</span><br><span class="line">        <span class="attr">"self"</span>: &#123;</span><br><span class="line">            <span class="attr">"href"</span>: <span class="string">"people"</span>,</span><br><span class="line">            <span class="attr">"title"</span>: <span class="string">"people"</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">"parent"</span>: &#123;</span><br><span class="line">            <span class="attr">"href"</span>: <span class="string">"/"</span>,</span><br><span class="line">            <span class="attr">"title"</span>: <span class="string">"home"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 试一下 <code>DELETE</code> http method</p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&gt; $ curl -X DELETE http://127.0.0.1:5000/people</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 你应该会得到</p>
                        <figure class="highlight json">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">"_status"</span>: <span class="string">"ERR"</span>,</span><br><span class="line">    <span class="attr">"_error"</span>: &#123;</span><br><span class="line">        <span class="attr">"code"</span>: <span class="number">405</span>,</span><br><span class="line">        <span class="attr">"message"</span>: <span class="string">"The method is not allowed for the requested URL."</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 因为我们在 <code>people</code> 里配置了
                          <code>&#39;resource_methods&#39;:
                            [&#39;GET&#39;, &#39;POST&#39;]</code>，除了
                          <code>GET</code>、<code>POST</code> 外，其他请求都是不成功的</p>
                        <p> 我们 <code>POST</code> 一些数据过去</p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line"><span class="comment"># POST 多条数据传 list，单条直接 json</span></span><br><span class="line">&gt; $ curl -X POST \</span><br><span class="line">    -H <span class="string">'Content-Type: application/json'</span> \</span><br><span class="line">    -d <span class="string">'[&#123;"firstname": "barack", "lastname": "obama"&#125;, &#123;"firstname": "mitt", "lastname": "romney"&#125;]'</span> \</span><br><span class="line">    http://127.0.0.1:5000/people</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 返回结果为</p>
                        <figure class="highlight json">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">"_status"</span>: <span class="string">"OK"</span>,</span><br><span class="line">    <span class="attr">"_items"</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">"_updated"</span>: <span class="string">"Fri, 23 Aug 2019 10:45:30 GMT"</span>,</span><br><span class="line">            <span class="attr">"_created"</span>: <span class="string">"Fri, 23 Aug 2019 10:45:30 GMT"</span>,</span><br><span class="line">            <span class="attr">"_etag"</span>: <span class="string">"fc6d5b3a95813465269c57d180ef1716f700cc6a"</span>,</span><br><span class="line">            <span class="attr">"_id"</span>: <span class="string">"5d5fc3cae85c86602304ef3b"</span>,</span><br><span class="line">            <span class="attr">"_links"</span>: &#123;</span><br><span class="line">                <span class="attr">"self"</span>: &#123;</span><br><span class="line">                    <span class="attr">"title"</span>: <span class="string">"person"</span>,</span><br><span class="line">                    <span class="attr">"href"</span>: <span class="string">"people/5d5fc3cae85c86602304ef3b"</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="attr">"_status"</span>: <span class="string">"OK"</span></span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="attr">"_updated"</span>: <span class="string">"Fri, 23 Aug 2019 10:45:30 GMT"</span>,</span><br><span class="line">            <span class="attr">"_created"</span>: <span class="string">"Fri, 23 Aug 2019 10:45:30 GMT"</span>,</span><br><span class="line">            <span class="attr">"_etag"</span>: <span class="string">"30761f80c263beb3b96fef0e07f5ec60ca4086e2"</span>,</span><br><span class="line">            <span class="attr">"_id"</span>: <span class="string">"5d5fc3cae85c86602304ef3c"</span>,</span><br><span class="line">            <span class="attr">"_links"</span>: &#123;</span><br><span class="line">                <span class="attr">"self"</span>: &#123;</span><br><span class="line">                    <span class="attr">"title"</span>: <span class="string">"person"</span>,</span><br><span class="line">                    <span class="attr">"href"</span>: <span class="string">"people/5d5fc3cae85c86602304ef3c"</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;,</span><br><span class="line">        <span class="attr">"_status"</span>: <span class="string">"OK"</span>&#125;</span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 查看一下 mongo</p>
                        <img src="/posts/python-eve-最佳实践/pic1.png">
                        <p> 已经自动创建了 <code>people</code> 表，并插入了刚刚传的两条数据</p>
                        <p> 我们请求一下 <code>item</code>，也就是 <code>people</code> 里的
                          <code>document</code></p>
                        <figure class="highlight bash">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&gt; $ curl -i http://127.0.0.1:5000/people/obama</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                        <p> 可以看到，我们直接用 <code>people/obama</code> 来请求资源，因为我们之前在
                          <code>people</code>
                          里定义了 <code>additional_lookup</code>，因此我们直接用
                          <code>last_name</code> 作为
                          <code>endpoint</code> 来访问，没有意外应该能得到下面的返回</p>
                        <figure class="highlight json">
                          <table>
                            <tr>
                              <td class="gutter">
                                <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre>
                              </td>
                              <td class="code">
                                <pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">"_id"</span>: <span class="string">"5d5fc3cae85c86602304ef3b"</span>,</span><br><span class="line">    <span class="attr">"firstname"</span>: <span class="string">"barack"</span>,</span><br><span class="line">    <span class="attr">"lastname"</span>: <span class="string">"obama"</span>,</span><br><span class="line">    <span class="attr">"_updated"</span>: <span class="string">"Fri, 23 Aug 2019 10:45:30 GMT"</span>,</span><br><span class="line">    <span class="attr">"_created"</span>: <span class="string">"Fri, 23 Aug 2019 10:45:30 GMT"</span>,</span><br><span class="line">    <span class="attr">"_etag"</span>: <span class="string">"fc6d5b3a95813465269c57d180ef1716f700cc6a"</span>,</span><br><span class="line">    <span class="attr">"_links"</span>: &#123;</span><br><span class="line">        <span class="attr">"self"</span>: &#123;</span><br><span class="line">            <span class="attr">"title"</span>: <span class="string">"person"</span>,</span><br><span class="line">            <span class="attr">"href"</span>: <span class="string">"people/5d5fc3cae85c86602304ef3b"</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">"parent"</span>: &#123;</span><br><span class="line">            <span class="attr">"title"</span>: <span class="string">"home"</span>,</span><br><span class="line">            <span class="attr">"href"</span>: <span class="string">"/"</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">"collection"</span>: &#123;</span><br><span class="line">            <span class="attr">"title"</span>: <span class="string">"people"</span>,</span><br><span class="line">            <span class="attr">"href"</span>: <span class="string">"people"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre>
                              </td>
                            </tr>
                          </table>
                        </figure>
                      </li>
                    </ul>
                    <h2 id="源码分析"><a href="#源码分析" class="headerlink"
                                                                                                      title="源码分析"></a>源码分析
                    </h2>
                    <p>Eve 的目录结构如下</p>
                    <figure class="highlight plain">
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line">eve</span><br><span class="line">├── io/</span><br><span class="line">├── methods/</span><br><span class="line">├── tests/</span><br><span class="line">├── __init__.py</span><br><span class="line">├── auth.py</span><br><span class="line">├── default_settings.py</span><br><span class="line">├── defaults.py</span><br><span class="line">├── endpoints.py</span><br><span class="line">├── exceptions.py</span><br><span class="line">├── flaskapp.py</span><br><span class="line">├── logging.py</span><br><span class="line">├── render.py</span><br><span class="line">├── utils.py</span><br><span class="line">├── validation.py</span><br><span class="line">└── versioning.py</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>这里不会一一详解，只会分析和配置比较相关的，影响开发的部分，部分分析会在注释里呈现</p>
                    <h3 id="endpoints"><a href="#endpoints" class="headerlink"
                                                                                                      title="endpoints"></a>endpoints
                    </h3>
                    <p>Eve 初始化的时候 <code>__init__()</code> 方法会调用
                      <code>register_resource()</code>
                      方法来注册 <code>resource</code> 信息</p>
                    <figure class="highlight python">
                      <figcaption><span>flaskapp.py __init__()</span>
                      </figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="comment"># Use a snapshot of the DOMAIN setup for iteration so</span></span><br><span class="line"><span class="comment"># further insertion of versioned resources do not</span></span><br><span class="line"><span class="comment"># cause a RuntimeError due to the change of size of</span></span><br><span class="line"><span class="comment"># the dict</span></span><br><span class="line">domain_copy = copy.deepcopy(self.config[<span class="string">"DOMAIN"</span>])</span><br><span class="line"><span class="keyword">for</span> resource, settings <span class="keyword">in</span> domain_copy.items():</span><br><span class="line">    self.register_resource(resource, settings)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 这里 self.config 就是 settings.py 里的配置，self.config['DOMAIN'] 就是 DOMAIN = &#123;'people': people&#125;</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><code>self.register_resource()</code> 方法会调用
                      <code>self._add_resource_url_rules(resource,
                        settings)</code>，绑定
                      <code>endpoint url</code> 和 <code>endpoint method</code>
                    </p>
                    <figure class="highlight python">
                      <figcaption><span>flaskapp.py register_resource()</span>
                      </figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="comment"># set up resource</span></span><br><span class="line">self._set_resource_defaults(resource, settings)</span><br><span class="line">self._validate_resource_settings(resource, settings)</span><br><span class="line">self._add_resource_url_rules(resource, settings)  <span class="comment"># 就是它</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><code>_add_resource_url_rules()</code> 实现如下</p>
                    <figure class="highlight python">
                      <figcaption><span>_add_resource_url_rules()</span>
                      </figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">_add_resource_url_rules</span><span class="params">(self, resource, settings)</span>:</span></span><br><span class="line">    <span class="string">""" Builds the API url map for one resource. Methods are enabled for</span></span><br><span class="line"><span class="string">    each mapped endpoint, as configured in the settings.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.5</span></span><br><span class="line"><span class="string">        Don't add resource to url rules if it's flagged as internal.</span></span><br><span class="line"><span class="string">        Strip regexes out of config.URLS helper. Closes #466.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionadded:: 0.2</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    self.config[<span class="string">"SOURCES"</span>][resource] = settings[<span class="string">"datasource"</span>]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> settings[<span class="string">"internal_resource"</span>]:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">    url = <span class="string">"%s/%s"</span> % (self.api_prefix, settings[<span class="string">"url"</span>])</span><br><span class="line"></span><br><span class="line">    pretty_url = settings[<span class="string">"url"</span>]</span><br><span class="line">    <span class="keyword">if</span> <span class="string">"&lt;"</span> <span class="keyword">in</span> pretty_url:</span><br><span class="line">        pretty_url = (</span><br><span class="line">            pretty_url[: pretty_url.index(<span class="string">"&lt;"</span>) + <span class="number">1</span>]</span><br><span class="line">            + pretty_url[pretty_url.rindex(<span class="string">":"</span>) + <span class="number">1</span> :]</span><br><span class="line">        )</span><br><span class="line">    self.config[<span class="string">"URLS"</span>][resource] = pretty_url</span><br><span class="line"></span><br><span class="line">    <span class="comment"># resource endpoint</span></span><br><span class="line">    <span class="comment"># 这里调用 flask 的 add_url_rule() 方法绑定 resource url 和 method</span></span><br><span class="line">    <span class="comment"># collection_endpoint 函数是对 http method 的一些封装，下面会讲到</span></span><br><span class="line">    endpoint = resource + <span class="string">"|resource"</span></span><br><span class="line">    self.add_url_rule(</span><br><span class="line">        url,</span><br><span class="line">        endpoint,</span><br><span class="line">        view_func=collections_endpoint,</span><br><span class="line">        methods=settings[<span class="string">"resource_methods"</span>] + [<span class="string">"OPTIONS"</span>],</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="comment"># item endpoint</span></span><br><span class="line">    <span class="comment"># 这里调用 flask 的 add_url_rule() 方法绑 item url 和 method</span></span><br><span class="line">    <span class="keyword">if</span> settings[<span class="string">"item_lookup"</span>]:</span><br><span class="line">        item_url = <span class="string">"%s/&lt;%s:%s&gt;"</span> % (</span><br><span class="line">            url,</span><br><span class="line">            settings[<span class="string">"item_url"</span>],</span><br><span class="line">            settings[<span class="string">"item_lookup_field"</span>],</span><br><span class="line">        )</span><br><span class="line"></span><br><span class="line">        <span class="comment"># item_endpoint 函数是对 http method 的一些封装，下面会讲到</span></span><br><span class="line">        endpoint = resource + <span class="string">"|item_lookup"</span></span><br><span class="line">        self.add_url_rule(</span><br><span class="line">            item_url,</span><br><span class="line">            endpoint,</span><br><span class="line">            view_func=item_endpoint,</span><br><span class="line">            methods=settings[<span class="string">"item_methods"</span>] + [<span class="string">"OPTIONS"</span>],</span><br><span class="line">        )</span><br><span class="line">        <span class="keyword">if</span> <span class="string">"PATCH"</span> <span class="keyword">in</span> settings[<span class="string">"item_methods"</span>]:</span><br><span class="line">            <span class="comment"># support for POST with X-HTTP-Method-Override header for</span></span><br><span class="line">            <span class="comment"># clients not supporting PATCH. Also see item_endpoint() in</span></span><br><span class="line">            <span class="comment"># endpoints.py</span></span><br><span class="line">            endpoint = resource + <span class="string">"|item_post_override"</span></span><br><span class="line">            self.add_url_rule(</span><br><span class="line">                item_url, endpoint, view_func=item_endpoint, methods=[<span class="string">"POST"</span>]</span><br><span class="line">            )</span><br><span class="line"></span><br><span class="line">        <span class="comment"># also enable an alternative lookup/endpoint if allowed</span></span><br><span class="line">        lookup = settings.get(<span class="string">"additional_lookup"</span>)</span><br><span class="line">        <span class="keyword">if</span> lookup:</span><br><span class="line">            l_type = settings[<span class="string">"schema"</span>][lookup[<span class="string">"field"</span>]][<span class="string">"type"</span>]</span><br><span class="line">            <span class="keyword">if</span> l_type == <span class="string">"integer"</span>:</span><br><span class="line">                item_url = <span class="string">"%s/&lt;int:%s&gt;"</span> % (url, lookup[<span class="string">"field"</span>])</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                item_url = <span class="string">"%s/&lt;%s:%s&gt;"</span> % (url, lookup[<span class="string">"url"</span>], lookup[<span class="string">"field"</span>])</span><br><span class="line">            endpoint = resource + <span class="string">"|item_additional_lookup"</span></span><br><span class="line">            self.add_url_rule(</span><br><span class="line">                item_url,</span><br><span class="line">                endpoint,</span><br><span class="line">                view_func=item_endpoint,</span><br><span class="line">                methods=[<span class="string">"GET"</span>, <span class="string">"OPTIONS"</span>],</span><br><span class="line">            )</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p><code>collections_endpoint</code> 和
                      <code>item_endpoint</code> 封装了
                      <strong>http method</strong> 对应的 <strong>mongo io
                        操作</strong></p>
                    <figure class="highlight python">
                      <figcaption><span>endpoints.py</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">collections_endpoint</span><span class="params">(**lookup)</span>:</span></span><br><span class="line">    <span class="string">""" Resource endpoint handler</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    :param url: the url that led here</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.3</span></span><br><span class="line"><span class="string">       Pass lookup query down to delete_resource, so it can properly process</span></span><br><span class="line"><span class="string">       sub-resources.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.2</span></span><br><span class="line"><span class="string">       Relying on request.endpoint to retrieve the resource being consumed.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.1.1</span></span><br><span class="line"><span class="string">       Relying on request.path for determining the current endpoint url.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.0.7</span></span><br><span class="line"><span class="string">       Using 'utils.request_method' helper function now.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.0.6</span></span><br><span class="line"><span class="string">       Support for HEAD requests</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.0.2</span></span><br><span class="line"><span class="string">        Support for DELETE resource method.</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line"></span><br><span class="line">    resource = _resource()</span><br><span class="line">    response = <span class="literal">None</span></span><br><span class="line">    method = request.method</span><br><span class="line">    <span class="keyword">if</span> method <span class="keyword">in</span> (<span class="string">"GET"</span>, <span class="string">"HEAD"</span>):</span><br><span class="line">        response = get(resource, lookup)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"POST"</span>:</span><br><span class="line">        response = post(resource)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"DELETE"</span>:</span><br><span class="line">        response = delete(resource, lookup)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"OPTIONS"</span>:</span><br><span class="line">        send_response(resource, response)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        abort(<span class="number">405</span>)</span><br><span class="line">    <span class="keyword">return</span> send_response(resource, response)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">item_endpoint</span><span class="params">(**lookup)</span>:</span></span><br><span class="line">    <span class="string">""" Item endpoint handler</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    :param url: the url that led here</span></span><br><span class="line"><span class="string">    :param lookup: sub resource query</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.2</span></span><br><span class="line"><span class="string">       Support for sub-resources.</span></span><br><span class="line"><span class="string">       Relying on request.endpoint to retrieve the resource being consumed.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.1.1</span></span><br><span class="line"><span class="string">       Relying on request.path for determining the current endpoint url.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.1.0</span></span><br><span class="line"><span class="string">       Support for PUT method.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.0.7</span></span><br><span class="line"><span class="string">       Using 'utils.request_method' helper function now.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.0.6</span></span><br><span class="line"><span class="string">       Support for HEAD requests</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    resource = _resource()</span><br><span class="line">    response = <span class="literal">None</span></span><br><span class="line">    method = request.method</span><br><span class="line">    <span class="keyword">if</span> method <span class="keyword">in</span> (<span class="string">"GET"</span>, <span class="string">"HEAD"</span>):</span><br><span class="line">        response = getitem(resource, **lookup)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"PATCH"</span>:</span><br><span class="line">        response = patch(resource, **lookup)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"PUT"</span>:</span><br><span class="line">        response = put(resource, **lookup)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"DELETE"</span>:</span><br><span class="line">        response = deleteitem(resource, **lookup)</span><br><span class="line">    <span class="keyword">elif</span> method == <span class="string">"OPTIONS"</span>:</span><br><span class="line">        send_response(resource, response)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        abort(<span class="number">405</span>)</span><br><span class="line">    <span class="keyword">return</span> send_response(resource, response)</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>对应 <code>get</code>、<code>put</code> 等具体实现在
                      <code>method</code> 文件夹下</p>
                    <h2 id="使用建议"><a href="#使用建议" class="headerlink"
                                                                                                      title="使用建议"></a>使用建议
                    </h2>
                    <p>在我的需求场景中，mongo 表有一个唯一标识字段
                      <code>urs</code>，<strong>查询</strong>
                      操作直接通过这个字段查询，<strong>插入</strong>
                      数据时，已存在则覆盖(upsert)，不存在则直接插入(insert)，<strong>删除</strong>
                      时根据这个字段删除</p>
                    <p>但是因为 <code>POST</code> 只有
                      <code>collections_endpoint</code> 实现，而且还不能够
                      <code>upsert</code> 只能 <code>insert</code>，所以插入需要用
                      <code>PUT</code> 来做，因此
                      <code>settings.py</code> 里只设置 <code>item_methods</code>
                    </p>
                    <p>settings 大致如下:</p>
                    <figure class="highlight python">
                      <figcaption><span>settings.py</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> schemas <span class="keyword">import</span> urs_schema</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># config =========================================================</span></span><br><span class="line"><span class="comment"># MONGO_HOST = os.environ.get('MONGO_HOST')</span></span><br><span class="line"><span class="comment"># MONGO_PORT = int(os.environ.get('MONGO_PORT'))</span></span><br><span class="line">MONGO_URI = os.environ.get(<span class="string">'MONGO_URI'</span>)</span><br><span class="line">MONGO_USERNAME = os.environ.get(<span class="string">'MONGO_USERNAME'</span>)</span><br><span class="line">MONGO_PASSWORD = os.environ.get(<span class="string">'MONGO_PASSWORD'</span>)</span><br><span class="line">MONGO_AUTH_SOURCE = os.environ.get(<span class="string">'MONGO_AUTH_SOURCE'</span>)</span><br><span class="line">MONGO_DBNAME = os.environ.get(<span class="string">'MONGO_DBNAME'</span>)</span><br><span class="line"></span><br><span class="line">IF_MATCH = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># domain =========================================================</span></span><br><span class="line">offline_trading_account = &#123;</span><br><span class="line">    <span class="string">'item_title'</span>: <span class="string">'urs'</span>,</span><br><span class="line">    <span class="string">'id_field'</span>: <span class="string">'urs'</span>,  <span class="comment"># 比较关键的设置，将 id_field 设为你的唯一字段</span></span><br><span class="line">    <span class="string">'item_url'</span>: <span class="string">'regex("[\s\S]+")'</span>,</span><br><span class="line">    <span class="string">'item_lookup_field'</span>: <span class="string">'urs'</span>,</span><br><span class="line">    <span class="string">'additional_lookup'</span>: &#123;</span><br><span class="line">        <span class="string">'url'</span>: <span class="string">'regex("[\s\S]+")'</span>,</span><br><span class="line">        <span class="string">'field'</span>: <span class="string">'urs'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">'resource_methods'</span>: [],  <span class="comment"># resource_methods 为空</span></span><br><span class="line">    <span class="string">'item_methods'</span>: [<span class="string">'GET'</span>, <span class="string">'PUT'</span>, <span class="string">'DELETE'</span>],</span><br><span class="line">    <span class="string">'schema'</span>: urs_schema</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">DOMAIN = &#123;os.environ.get(<span class="string">'MONGO_COLLECTION'</span>): offline_trading_account&#125;</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>在上面的快速开始中，你可能注意到，插入数据时，eve 会自动给你加上
                      <code>_updated</code>、<code>_created</code> 的 date
                      格式字段，你想动它又不知如何下手；还有它返回的
                      json 格式，可能并不符合需求。这时你就要利用到 <strong>hook</strong> 的特性了。Eve
                      提供了一系列 <strong>hook
                        函数</strong> 让你进行操作，这里贴上我定义的 hook 函数供参考，具体用法跟如何定义参考 Eve
                      文档</p>
                    <figure class="highlight python">
                      <figcaption><span>hooks.py</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> request, abort</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">before_insert_urs</span><span class="params">(items)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> items:</span><br><span class="line">        item[<span class="string">'updateTime'</span>] = datetime.now().strftime(<span class="string">'%Y-%m-%d %H:%M:%S'</span>)</span><br><span class="line">        item.pop(<span class="string">'_created'</span>)</span><br><span class="line">        item.pop(<span class="string">'_updated'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">before_replace_urs</span><span class="params">(item, original)</span>:</span></span><br><span class="line">    item[<span class="string">'updateTime'</span>] = datetime.now().strftime(<span class="string">'%Y-%m-%d %H:%M:%S'</span>)</span><br><span class="line">    item.pop(<span class="string">'_created'</span>)</span><br><span class="line">    item.pop(<span class="string">'_updated'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">after_fetched_urs</span><span class="params">(response)</span>:</span></span><br><span class="line">    response.pop(<span class="string">'_id'</span>)</span><br><span class="line">    response[<span class="string">'_status'</span>] = <span class="string">'OK'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">before_get_put_delete</span><span class="params">(resource, _request, lookup)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> _request.headers.get(<span class="string">'X-NEProxy-User'</span>) <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        abort(<span class="number">403</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">after_get_put_delete</span><span class="params">(resoure, _request, payload)</span>:</span></span><br><span class="line">    code = payload.status_code</span><br><span class="line">    data = payload.json.copy()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> len(data) == <span class="number">0</span>:</span><br><span class="line">        data[<span class="string">'_status'</span>] = <span class="string">'OK'</span></span><br><span class="line">    <span class="keyword">if</span> data.get(<span class="string">'_created'</span>):</span><br><span class="line">        data.pop(<span class="string">'_created'</span>)</span><br><span class="line">    <span class="keyword">if</span> data.get(<span class="string">'_updated'</span>):</span><br><span class="line">        data.pop(<span class="string">'_updated'</span>)</span><br><span class="line">    <span class="keyword">if</span> data.get(<span class="string">'_links'</span>):</span><br><span class="line">        data.pop(<span class="string">'_links'</span>)</span><br><span class="line"></span><br><span class="line">    payload.json.clear()</span><br><span class="line">    payload.json[<span class="string">'code'</span>] = code</span><br><span class="line">    payload.json[<span class="string">'data'</span>] = data</span><br><span class="line"></span><br><span class="line">    payload.status_code = <span class="number">200</span></span><br><span class="line">    payload.data = json.dumps(payload.json).encode()</span><br><span class="line">    payload.headers[<span class="string">'Access-Control-Allow-Origin'</span>] = <span class="string">'*'</span></span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>在 app 对象里注册 hook 函数</p>
                    <figure class="highlight python">
                      <figcaption><span>init.py</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="keyword">from</span> eve <span class="keyword">import</span> Eve</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> jsonify</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> hooks <span class="keyword">import</span> (</span><br><span class="line">    before_get_put_delete,</span><br><span class="line">    before_insert_urs,</span><br><span class="line">    before_replace_urs,</span><br><span class="line">    after_fetched_urs,</span><br><span class="line">    after_get_put_delete</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">register_event_hook</span><span class="params">(app)</span>:</span></span><br><span class="line">    <span class="comment"># 这里 req131313_offline_trading_account 要和你定义的 resource 名一致，也就是 DOMAIN 的 key</span></span><br><span class="line">    app.on_insert_req131313_offline_trading_account += before_insert_urs</span><br><span class="line">    app.on_replace_req131313_offline_trading_account += before_replace_urs</span><br><span class="line">    app.on_fetched_item_req131313_offline_trading_account += after_fetched_urs</span><br><span class="line">    app.on_pre_GET += before_get_put_delete</span><br><span class="line">    app.on_pre_PUT += before_get_put_delete</span><br><span class="line">    app.on_pre_DELETE += before_get_put_delete</span><br><span class="line">    app.on_post_GET += after_get_put_delete</span><br><span class="line">    app.on_post_PUT += after_get_put_delete</span><br><span class="line">    app.on_post_DELETE += after_get_put_delete</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">create_app</span><span class="params">()</span>:</span></span><br><span class="line">    app = Eve()</span><br><span class="line">    register_event_hook(app)</span><br><span class="line">    <span class="keyword">return</span> app</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <p>hook 的原理其实就是在执行 <code>method</code> 里的函数时(如
                      <code>get</code>、<code>put</code>)，通过 <code>getattr</code>
                      获取到
                      <code>app</code> 对象注册的 hook 函数，然后调用执行，下面是代码片段</p>
                    <figure class="highlight python">
                      <figcaption><span>methods/common.py</span></figcaption>
                      <table>
                        <tr>
                          <td class="gutter">
                            <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre>
                          </td>
                          <td class="code">
                            <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">pre_event</span><span class="params">(f)</span>:</span></span><br><span class="line">    <span class="string">""" Enable a Hook pre http request.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.6</span></span><br><span class="line"><span class="string">       Enable callback hooks for HEAD requests.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionchanged:: 0.4</span></span><br><span class="line"><span class="string">       Merge 'sub_resource_lookup' (args[1]) with kwargs, so http methods can</span></span><br><span class="line"><span class="string">       all enjoy the same signature, and data layer find methods can seemingly</span></span><br><span class="line"><span class="string">       process both kind of queries.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .. versionadded:: 0.2</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @wraps(f)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">decorated</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">        method = request.method</span><br><span class="line">        <span class="keyword">if</span> method == <span class="string">"HEAD"</span>:</span><br><span class="line">            method = <span class="string">"GET"</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 这里拿到的 event_name 就是我们 app 注册的 hook 函数名</span></span><br><span class="line">        event_name = <span class="string">"on_pre_"</span> + method</span><br><span class="line">        resource = args[<span class="number">0</span>] <span class="keyword">if</span> args <span class="keyword">else</span> <span class="literal">None</span></span><br><span class="line">        gh_params = ()</span><br><span class="line">        rh_params = ()</span><br><span class="line">        combined_args = kwargs</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> len(args) &gt; <span class="number">1</span>:</span><br><span class="line">            combined_args.update(args[<span class="number">1</span>].items())</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> method <span class="keyword">in</span> (<span class="string">"GET"</span>, <span class="string">"PATCH"</span>, <span class="string">"DELETE"</span>, <span class="string">"PUT"</span>):</span><br><span class="line">            gh_params = (resource, request, combined_args)</span><br><span class="line">            rh_params = (request, combined_args)</span><br><span class="line">        <span class="keyword">elif</span> method <span class="keyword">in</span> (<span class="string">"POST"</span>,):</span><br><span class="line">            <span class="comment"># POST hook does not support the kwargs argument</span></span><br><span class="line">            gh_params = (resource, request)</span><br><span class="line">            rh_params = (request,)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># general hook</span></span><br><span class="line">        <span class="comment"># 通过 getattr 调用</span></span><br><span class="line">        getattr(app, event_name)(*gh_params)</span><br><span class="line">        <span class="keyword">if</span> resource:</span><br><span class="line">            <span class="comment"># resource hook</span></span><br><span class="line">            getattr(app, event_name + <span class="string">"_"</span> + resource)(*rh_params)</span><br><span class="line"></span><br><span class="line">        r = f(resource, **combined_args)</span><br><span class="line">        <span class="keyword">return</span> r</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> decorated</span><br></pre>
                          </td>
                        </tr>
                      </table>
                    </figure>
                    <h1 id="结语"><a href="#结语" class="headerlink"
                                                                                                      title="结语"></a>结语
                    </h1>
                    <p>在看了大部分的源码和文档之后，总结一下，Eve 这个框架实现的并不复杂，思想上非常符合 restful
                      风格，可以说是一个通用的，以配置为驱动的
                      restful 框架，但是也仅仅是通用而已了，因为它的 endpoint method
                      已经封装好了，你想要做一些改动，比如入参或返回，要通过 hook
                      来做，这样就很不友好而且很不规范，还仅支持 mongo，那就只能写些小接口玩玩了。或许这就是它原本的初衷呢？</p>

                  </div>

                  <div>

                    <div>

                      <div
                                                                                                      style="text-align:center;color: #ccc;font-size:14px;">
                        ---------------------------------END---------------------------------
                      </div>

                    </div>

                  </div>

                  <div>
                    <div
                                                                                                    style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
                      <div>手抖一下？</div>
                      <button id="rewardButton" disable="enable"
                                                                                                      onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
                        <span>献爱心</span>
                      </button>
                      <div id="QR" style="display: none;">

                        <div id="wechat" style="display: inline-block">
                          <img id="wechat_qr" src="/images/wx_pay1.png"
                                                                                                          alt="tankeryang WechatPay">
                          <p>WechatPay</p>
                        </div>

                      </div>
                    </div>

                  </div>

                  <footer class="post-footer">

                    <div class="post-tags">

                      <a href="/tags/python/" rel="tag"><i
                                                                                                        class="fa fa-tag"></i>
                        python</a>

                      <a href="/tags/python-eve/" rel="tag"><i
                                                                                                        class="fa fa-tag"></i>
                        python-eve</a>

                      <a href="/tags/web/" rel="tag"><i class="fa fa-tag"></i>
                        web</a>

                    </div>

                    <div class="post-widgets">

                      <div id="needsharebutton-postbottom">
                        <span class="btn">
                          <i class="fa fa-share-alt" aria-hidden="true"></i>
                        </span>
                      </div>

                    </div>

                    <div class="post-nav">
                      <div class="post-nav-next post-nav-item">

                        <a href="/posts/docker配置TLS认证开启远程访问/" rel="next"
                                                                                                        title="docker配置TLS认证开启远程访问">
                          <i class="fa fa-chevron-left"></i> docker配置TLS认证开启远程访问
                        </a>

                      </div>

                      <span class="post-nav-divider"></span>

                      <div class="post-nav-prev post-nav-item">

                      </div>
                    </div>

                  </footer>
                </div>

              </article>

              <div class="post-spread">

                <!-- Go to www.addthis.com/dashboard to customize your tools -->
                <div class="addthis_inline_share_toolbox">
                  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-59b14058bcac3b78"
                                                                                                  async="async">
                  </script>
                </div>

              </div>
            </div>

          </div>

          <div class="comments" id="comments">
          </div>

        </div>

        <div class="sidebar-toggle">
          <div class="sidebar-toggle-line-wrap">
            <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
            <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
            <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
          </div>
        </div>

        <aside id="sidebar" class="sidebar">

          <div id="sidebar-dimmer"></div>

          <div class="sidebar-inner">

            <ul class="sidebar-nav motion-element">
              <li class="sidebar-nav-toc sidebar-nav-active"
                                                                                              data-target="post-toc-wrap">
                文章目录
              </li>
              <li class="sidebar-nav-overview" data-target="site-overview-wrap">
                站点概览
              </li>
            </ul>

            <section class="site-overview-wrap sidebar-panel">
              <div class="site-overview">
                <div class="site-author motion-element" itemprop="author" itemscope
                                                                                                itemtype="http://schema.org/Person">

                  <a href="/" class="site-author-image" rel="start"
                                                                                                  style="border:none">
                    <img class="site-author-image" itemprop="image" src="/uploads/girl.jpeg"
                                                                                                    alt="tankeryang">
                  </a>

                  <p class="site-author-name" itemprop="name">tankeryang</p>
                  <p class="site-description motion-element"
                                                                                                  itemprop="description">
                    汝亦知射乎？吾射不亦精乎？</p>
                </div>

                <nav class="site-state motion-element">

                  <div class="site-state-item site-state-posts">

                    <a href="/archives/">

                      <span class="site-state-item-count">16</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>

                  <div class="site-state-item site-state-categories">
                    <a href="/categories/index.html">
                      <span class="site-state-item-count">7</span>
                      <span class="site-state-item-name">分类</span>
                    </a>
                  </div>

                  <div class="site-state-item site-state-tags">
                    <a href="/tags/index.html">
                      <span class="site-state-item-count">28</span>
                      <span class="site-state-item-name">标签</span>
                    </a>
                  </div>

                </nav>

                <div class="links-of-author motion-element">

                  <span class="links-of-author-item">
                    <a href="https://github.com/tankeryang" target="_blank"
                                                                                                    title="GitHub">

                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>

                  <span class="links-of-author-item">
                    <a href="mailto:youngzyang@outlook.com" target="_blank"
                                                                                                    title="E-Mail">

                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>

                </div>

                <div class="cc-license motion-element" itemprop="license">
                  <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity"
                                                                                                  target="_blank">
                    <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
                  </a>
                </div>

                <div
                                                                                                class="links-of-blogroll motion-element links-of-blogroll-block">
                  <div class="links-of-blogroll-title">
                    <i class="fa  fa-fw fa-link"></i>
                    博客镜像 & 友情链接
                  </div>
                  <ul class="links-of-blogroll-list">

                    <li class="links-of-blogroll-item">
                      <a href="https://tankeryang.github.io" title="淦 - github"
                                                                                                      target="_blank">淦
                        - github</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://tankeryang.coding.me" title="淦 - coding"
                                                                                                      target="_blank">淦
                        - coding</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="http://tankeryang.gitee.io" title="淦 - gitee"
                                                                                                      target="_blank">淦
                        - gitee</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://deeeeeeeee.github.io" title="未知"
                                                                                                      target="_blank">未知</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://www.tiexo.cn/" title="简单可依赖"
                                                                                                      target="_blank">简单可依赖</a>
                    </li>

                    <li class="links-of-blogroll-item">
                      <a href="https://darrenliuwei.com" title="刘伟"
                                                                                                      target="_blank">刘伟</a>
                    </li>

                  </ul>
                </div>

              </div>
            </section>

            <!--noindex-->
            <section
                                                                                            class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
              <div class="post-toc">

                <div class="post-toc-content">
                  <ol class="nav">
                    <li class="nav-item nav-level-1"><a class="nav-link"
                                                                                                      href="#Eve-简介"><span
                                                                                                        class="nav-number">1.</span>
                        <span class="nav-text">Eve 简介
                        </span></a>
                      <ol class="nav-child">
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#快速开始"><span
                                                                                                            class="nav-number">1.1.</span>
                            <span class="nav-text">快速开始</span></a></li>
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#源码分析"><span
                                                                                                            class="nav-number">1.2.</span>
                            <span class="nav-text">源码分析</span></a>
                          <ol class="nav-child">
                            <li class="nav-item nav-level-3"><a class="nav-link"
                                                                                                              href="#endpoints"><span
                                                                                                                class="nav-number">1.2.1.</span>
                                <span class="nav-text">endpoints
                                </span></a></li>
                          </ol>
                        </li>
                        <li class="nav-item nav-level-2"><a class="nav-link"
                                                                                                          href="#使用建议"><span
                                                                                                            class="nav-number">1.3.</span>
                            <span class="nav-text">使用建议</span></a></li>
                      </ol>
                    </li>
                    <li class="nav-item nav-level-1"><a class="nav-link"
                                                                                                      href="#结语"><span
                                                                                                        class="nav-number">2.</span>
                        <span class="nav-text">结语</span></a></li>
                  </ol>
                </div>

              </div>
            </section>
            <!--/noindex-->

            <div class="back-to-top">
              <i class="fa fa-arrow-up"></i>

              <span id="scrollpercent"><span>0</span>%</span>

            </div>

          </div>
        </aside>

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <hr>
        <div class="copyright">&copy; 2017 &mdash; <span
                                                                                          itemprop="copyrightYear">2019</span>
          <span class="with-love">
            <i class="fa fa-cog fa-spin fa-1x fa-fw"></i>
          </span>
          <span class="author" itemprop="copyrightHolder">tankeryang</span>

          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-area-chart"></i>
          </span>

          <span title="total count">131k</span>

          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-coffee"></i>
          </span>

          <span title="total time">4:51</span>

        </div>

        <div class="powered-by">Powered by — <a class="theme-link" target="_blank"
                                                                                          href="https://hexo.io">Hexo</a>
        </div>

        <span class="post-meta-divider">|</span>

        <div class="theme-info">theme &mdash; <a class="theme-link" target="_blank"
                                                                                          href="https://github.com/theme-next/hexo-theme-next">NexT.Mist</a>
          v6.0.1</div>

        <div class="busuanzi-count">
          <script async
                                                                                          src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
          </script>

          <span class="site-uv">
            <i class="fa fa-user"></i>
            <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
            visitors
          </span>

        </div>

      </div>
    </footer>

  </div>

  <script type="text/javascript">
    if (Object.prototype.toString.call(window.Promise) !==
      '[object Function]') {
      window.Promise = null;
    }

  </script>

  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript"
                                                                                  src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7">
  </script>

  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1">
  </script>

  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1">
  </script>

  <script type="text/javascript"
                                                                                  src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5">
  </script>

  <script type="text/javascript"
                                                                                  src="/lib/reading_progress/reading_progress.js">
  </script>

  <script type="text/javascript" src="/js/src/utils.js?v=6.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.1"></script>

  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.1"></script>
  <script type="text/javascript" src="/js/src/post-details.js?v=6.0.1"></script>

  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.1"></script>

  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>

  <script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.indexOf(item) > -1;
    });
    new Valine({
      el: '#comments',
      verify: true,
      notify: false,
      appId: 'NiFbgAF3vRyR2BayGJOswb21-gzGzoHsz',
      appKey: 'xGF7qavyOOQGtVACk06SnLrW',
      placeholder: '填上邮箱可以收到回复的邮件提醒哦～',
      avatar: 'retro',
      guest_info: guest,
      pageSize: '10' || 10,
    });

  </script>

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;
    var onPopupClose = function(e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append(
          '<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      // start loading animation
      $("body")
        .append(
          '<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css(
        'text-align', 'center');
      // ref: https://github.com/ForbesLindesay/unescape-html
      var unescapeHtml = function(html) {
        return String(html)
          .replace(/&quot;/g, '"')
          .replace(/&#39;/g, '\'')
          .replace(/&#x3A;/g, ':')
          // replace all the other &#x; chars
          .replace(/&#(\d+);/g, function(m, p) {
            return String.fromCharCode(p);
          })
          .replace(/&lt;/g, '<')
          .replace(/&gt;/g, '>')
          .replace(/&amp;/g, '&');
      };
      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(
                  /<[^>]+>/g, "");
                content = unescapeHtml(content);
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if (title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text,
                      caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0,
                        position = [],
                        index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word,
                          startPosition)) > -1) {
                        index.push({
                          position: position,
                          word: word
                        });
                        startPosition = position + wordLen;
                      }
                      return index;
                    }
                    indexOfTitle = indexOfTitle.concat(
                      getIndexByWord(keyword,
                        titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(
                      getIndexByWord(keyword,
                        contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent
                    .length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length +
                      indexOfContent.length;
                  }
                }
                // show search results
                if (isMatch) {
                  // sort index by position of keyword
                  [indexOfTitle, indexOfContent].forEach(function(
                    index) {
                    index.sort(function(itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft
                        .position) {
                        return itemRight.position -
                          itemLeft.position;
                      } else {
                        return itemLeft.word.length -
                          itemRight.word.length;
                      }
                    });
                  });
                  // merge hits into slices
                  function mergeIntoSlice(text, start, end,
                  index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index
                      .length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({
                        position: position,
                        length: word.length
                      });
                      var wordEnd = position + word.length;
                      // move to next position of hit
                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }
                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0,
                      title.length, indexOfTitle));
                  }
                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent
                      .length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if (start < 0) {
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if (end > content.length) {
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content,
                      start, end, indexOfContent));
                  }
                  // sort slices in content by search text's count and hits' count
                  slicesOfContent.sort(function(sliceLeft,
                    sliceRight) {
                    if (sliceLeft.searchTextCount !==
                      sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount -
                        sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !==
                      sliceRight.hits.length) {
                      return sliceRight.hits.length -
                        sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight
                        .start;
                    }
                  });
                  // select top N slices in content
                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0,
                      upperBound);
                  }
                  // highlight title and content
                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function(hit) {
                      result += text.substring(prevEnd, hit
                        .position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' +
                        text.substring(hit.position, end) +
                        '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }
                  var resultItem = '';
                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl +
                      "' class='search-result-title'>" +
                      highlightKeyword(title, slicesOfTitle[0]) +
                      "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl +
                      "' class='search-result-title'>" + title +
                      "</a>";
                  }
                  slicesOfContent.forEach(function(slice) {
                    resultItem += "<a href='" + articleUrl +
                      "'>" +
                      "<p class=\"search-result\">" +
                      highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });
                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML =
                '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML =
                '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function(resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight
                  .searchTextCount) {
                  return resultRight.searchTextCount - resultLeft
                    .searchTextCount;
                } else if (resultLeft.hitCount !== resultRight
                  .hitCount) {
                  return resultRight.hitCount - resultLeft
                    .hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList =
                '<ul class=\"search-result-list\">';
              resultItems.forEach(function(result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }
          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function(event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }
          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');
          proceedsearch();
        }
      });
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function(event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

  </script>

  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>
    AV.initialize("NiFbgAF3vRyR2BayGJOswb21-gzGzoHsz",
      "xGF7qavyOOQGtVACk06SnLrW");

  </script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");
      $visitors.each(function() {
        entries.push($(this).attr("id").trim());
      });
      query.containedIn('url', entries);
      query.find()
        .done(function(results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';
          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }
          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);
            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for (var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if (countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function(object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);
      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(
                  counter.get('time'));
              },
              error: function(counter, error) {
                console.log(
                  'Failed to save Visitor num, with error message: ' +
                  error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(
                  newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }
    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });

  </script>

  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    pbOptions = {};
    pbOptions.iconStyle = "box";
    pbOptions.boxForm = "horizontal";
    pbOptions.position = "topCenter";
    pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
    new needShareButton('#needsharebutton-postbottom', pbOptions);

  </script>

  <script src="/lib/pangu/dist/pangu.min.js?v=3.3"></script>
  <script type="text/javascript">
    pangu.spacingPage();

  </script>

  <script type="text/javascript" src="/js/src/exturl.js?v=6.0.1"></script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config("");
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="custom_mathjax_source">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->

</body>

</html>
